package com.bsoft.gol.hcs.satisfaction.service;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.bsoft.gol.hcs.satisfaction.bean.request.QuerySurveyDeptListRequest;
import com.bsoft.gol.hcs.satisfaction.bean.response.*;
import com.bsoft.gol.hcs.satisfaction.dao.PatientSatisfactionSurveyDAO;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.DepartmentEnum;
import com.bsoft.gol.hcs.utils.excel.SatisfactionSurveyExcelUtil;
import ctd.net.rpc.Client;
import ctd.util.JSONUtils;
import hcn.base.Dept;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.atag.core.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping(value = "/api/auth")
public class SatisfactionSurveyExcelService {
    private final static Logger logger = LoggerFactory.getLogger(SatisfactionSurveyExcelService.class);

    @Autowired
    private PatientSatisfactionSurveyDAO patientSatisfactionSurveyDAO;

    /**
     * 导出excel
     */
    @RequestMapping(value = "exportStatisticsWorkExcel/download", method = RequestMethod.POST)
    @ResponseBody
    public void exportStatisticsWorkExcel(@RequestBody QuerySurveyDeptListRequest request, HttpServletRequest request1, HttpServletResponse response1) throws IOException {
        List<SurveyPlanWorkListResponse> planWorkListResponses = new ArrayList<>();
        QueryDeptTotalResponse queryDeptTotalResponse = patientSatisfactionSurveyDAO.queryDeptTotal(request);
//        if (CommonUtils.isNull(queryDeptTotalResponse.getTotalSum())){
//            queryDeptTotalResponse.setTotalSum("0");
//        }else {
//            Double aDouble = Double.valueOf(queryDeptTotalResponse.getTotalSum());
//            queryDeptTotalResponse.setTotalSum(String.valueOf(new BigDecimal(new Double(0)*100).setScale(2,RoundingMode.HALF_UP)));
//        }
        if (CommonUtils.isNull(queryDeptTotalResponse.getTotalSum())) {

            queryDeptTotalResponse.setTotalSum("0.00");
        } else {
            Double aDouble = Double.valueOf(queryDeptTotalResponse.getTotalSum());
            log.info("=================>aDouble" + aDouble);
            BigDecimal num = new BigDecimal(aDouble * 100);
            BigDecimal bigDecimal = num.setScale(2, RoundingMode.HALF_UP);
            queryDeptTotalResponse.setTotalSum(String.valueOf(bigDecimal));

        }
        log.info("==========================科室评价统计" + JSONUtils.writeValueAsString(queryDeptTotalResponse));
        List<SurveyPlanDeptListResponse> surveyPlanDeptListResponses = patientSatisfactionSurveyDAO.querySurveyDeptByDeptIdNew(request);
        log.info("查询输出打印=======================================》" + JSONUtils.writeValueAsString(surveyPlanDeptListResponses));
        for (SurveyPlanDeptListResponse surveyPlanDeptListResponse : surveyPlanDeptListResponses) {
            SurveyPlanWorkListResponse response = new SurveyPlanWorkListResponse();
            response.setOrgName("杭州市第三人民医院");
            //使用枚举 取数据
            response.setDepartmentId(DepartmentEnum.getDeptIdAndName(surveyPlanDeptListResponse.getDepartmentId()).get("id"));
            response.setDepartmentName(DepartmentEnum.getDeptIdAndName(surveyPlanDeptListResponse.getDepartmentId()).get("name"));
//            response.setDepartmentId(surveyPlanDeptListResponse.getDepartmentId());
//            response.setDepartmentName(surveyPlanDeptListResponse.getDepartmentName());
            response.setBack(surveyPlanDeptListResponse.getBack());
            response.setPush(surveyPlanDeptListResponse.getPush());
            log.info("科室======》" + JSONUtils.writeValueAsString(surveyPlanDeptListResponse.getC()));
            BigDecimal num = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getC())) {
                num = new BigDecimal(new Double(0) * 100);

            } else {
                num = new BigDecimal(surveyPlanDeptListResponse.getC() * 100);
            }

            BigDecimal bnum = num.setScale(2, RoundingMode.HALF_UP);
            response.setC(String.valueOf(bnum));

            BigDecimal d = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getD())) {
                d = new BigDecimal(new Double(0) * 100);

            } else {
                d = new BigDecimal(surveyPlanDeptListResponse.getD() * 100);
            }

            BigDecimal dmum = d.setScale(2, RoundingMode.HALF_UP);
            response.setD(String.valueOf(dmum));


            BigDecimal e = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getE())) {
                e = new BigDecimal(new Double(0) * 100);

            } else {
                e = new BigDecimal(surveyPlanDeptListResponse.getE() * 100);
            }

            BigDecimal Emum = e.setScale(2, RoundingMode.HALF_UP);
            response.setE(String.valueOf(Emum));

            if (CommonUtils.isNotEmpty(surveyPlanDeptListResponse.getDepartmentId())) {
                QuerySurveyDeptListRequest req = new QuerySurveyDeptListRequest();
                req.setDeptId(surveyPlanDeptListResponse.getDepartmentId());
                req.setQuestionnaireId(request.getQuestionnaireId());
                req.setBeginDate(request.getBeginDate());
                req.setEndDate(request.getEndDate());
                // List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = patientSatisfactionSurveyDAO.querySurveyAverByDeptId(req);
                List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = new ArrayList<>();
                response.setSurveyPlanTitleListResponses(surveyPlanTitleListResponses);
            }
            response.setQueryDeptTotalResponse(queryDeptTotalResponse);
            log.info("前端相应输出=====》" + JSONUtils.writeValueAsString(response));
            planWorkListResponses.add(response);
        }
        if (CollectionUtils.isEmpty(planWorkListResponses)) {
            throw new ServiceException("没有要导出的数据");
        }
        logger.info("planWorkListResponses======" + JSONUtils.writeValueAsString(planWorkListResponses));


        List<SurveyPlanWorkListResponseNew> returnResponse = new ArrayList<>();
        Map<String, List<SurveyPlanWorkListResponse>> map = new HashMap<>();
        for (SurveyPlanWorkListResponse response : planWorkListResponses) {
            try {
                String deptId = response.getDepartmentId();
                if (CommonUtils.isNotEmpty(deptId)) {
                    Dept dept = (Dept) Client.rpcInvoke("hcn.department", "getDeptByLocalDeptId", "61caaf61f5b2ba00a46fe46c", deptId);
                    log.info("DeptInfo=====》" + JSONUtils.writeValueAsString(dept));
                    if (ObjectUtil.isNotEmpty(dept)) {
                        String localDeptPid = dept.getLocalDeptPid();
                        if (StringUtils.isNotBlank(localDeptPid)) {
                            Dept localDept = (Dept) Client.rpcInvoke("hcn.department", "getDeptByLocalDeptId", "61caaf61f5b2ba00a46fe46c", localDeptPid);
                            log.info("localDeptPid=====》" + JSONUtils.writeValueAsString(localDept));
                            if (ObjectUtil.isNotEmpty(localDept)) {
                                response.setDeptPid(localDept.getLocalDeptId());
                                response.setDeptPidName(localDept.getName());
                                List<SurveyPlanWorkListResponse> surveyPlanWorkListResponses = map.get(localDept.getLocalDeptId());
                                if (CollectionUtils.isEmpty(surveyPlanWorkListResponses)){
                                    List<SurveyPlanWorkListResponse> s1 = new ArrayList<>();
                                    s1.add(response);
                                    map.put(localDept.getLocalDeptId(),s1);
                                }else {
                                    surveyPlanWorkListResponses.add(response);
                                    map.put(localDept.getLocalDeptId(),surveyPlanWorkListResponses);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("调用部门服务异常", e);
            }
        }

        log.info("map:{}", JSON.toJSONString(map));
        for (String key : map.keySet()) {
            SurveyPlanWorkListResponseNew snew = new SurveyPlanWorkListResponseNew();
            snew.setDepartmentId(key);
            snew.setDepartmentName(map.get(key).get(0).getDeptPidName());
            snew.setSurveyPlanWorkListResponses(map.get(key));
            returnResponse.add(snew);
        }

//        byte[] data = SatisfactionSurveyExcelUtil.getExcelAsByteArray(planWorkListResponses);
        byte[] data = SatisfactionSurveyExcelUtil.getExcelAsByteArrayNew(returnResponse);
        String fileName = null;
        fileName = URLEncoder.encode("满意度评价统计.xlsx", "UTF-8");
        response1.reset();
        response1.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response1.addHeader("Content-Length", "" + data.length);
        response1.setContentType("application/vnd.ms-excel;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response1.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();

    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "exportDoctorsWorkExcel/downloadNew", method = RequestMethod.POST)
    @ResponseBody
    public void exportDoctorsWorkExcelNew(@RequestBody QuerySurveyDeptListRequest request, HttpServletRequest request1, HttpServletResponse response1) throws IOException {

        List<SurveyPlanWorkListResponse> planWorkListResponses = new ArrayList<>();
        List<SurveyPlanDeptListResponse> surveyPlanDeptListResponses = patientSatisfactionSurveyDAO.queryDoctorWorkList1(request);
        for (SurveyPlanDeptListResponse surveyPlanDeptListResponse : surveyPlanDeptListResponses) {
            SurveyPlanWorkListResponse response = new SurveyPlanWorkListResponse();
            response.setOrgName("杭州市第三人民医院");
            response.setDoctorId(surveyPlanDeptListResponse.getDoctorId());
            response.setDoctorName(surveyPlanDeptListResponse.getDoctorName());
            response.setBack(surveyPlanDeptListResponse.getBack());
            response.setPush(surveyPlanDeptListResponse.getPush());
//            BigDecimal num = new BigDecimal(surveyPlanDeptListResponse.getC()*100);
//            BigDecimal bnum = num.setScale(2, RoundingMode.HALF_UP);
//            response.setC(String.valueOf(bnum));
            // Integer integer = patientSatisfactionSurveyDAO.queryDcotrorCount(surveyPlanDeptListResponse.getDoctorId(), request.getBeginDate(), request.getEndDate(), request.getQuestionnaireId());
            // log.info("输出===============》"+integer);
//            BigDecimal num = new BigDecimal(surveyPlanDeptListResponse.getC()*100);
            //double result = (double)  integer/Integer.valueOf(surveyPlanDeptListResponse.getBack());
//            BigDecimal num = new BigDecimal(result*100);
            BigDecimal num = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getC())) {
                num = new BigDecimal(new Double(0) * 100);

            } else {
                num = new BigDecimal(surveyPlanDeptListResponse.getC() * 100);
            }
            BigDecimal bnum = num.setScale(2, RoundingMode.HALF_UP);
            response.setC(String.valueOf(bnum));

            if (CommonUtils.isNotEmpty(surveyPlanDeptListResponse.getDoctorId())) {
                QuerySurveyDeptListRequest req = new QuerySurveyDeptListRequest();
                req.setDoctorId(surveyPlanDeptListResponse.getDoctorId());
                req.setQuestionnaireId(request.getQuestionnaireId());
                req.setBeginDate(request.getBeginDate());
                req.setEndDate(request.getEndDate());
                List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = patientSatisfactionSurveyDAO.querySurveyAverByDoctorId(req);
                response.setSurveyPlanTitleListResponses(surveyPlanTitleListResponses);
            }
            planWorkListResponses.add(response);
        }

        if (CollectionUtils.isEmpty(planWorkListResponses)) {
            throw new ServiceException("没有要导出的数据");
        }
        logger.info("planWorkListResponses======" + JSONUtils.writeValueAsString(planWorkListResponses));

        byte[] data = SatisfactionSurveyExcelUtil.getExcelAsByteArray2(planWorkListResponses);
        String fileName = null;
        fileName = URLEncoder.encode("医生满意度统计.xlsx", "UTF-8");
        response1.reset();
        response1.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response1.addHeader("Content-Length", "" + data.length);
        response1.setContentType("application/vnd.ms-excel;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response1.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();

    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "exportDoctorsWorkExcel/download", method = RequestMethod.POST)
    @ResponseBody
    public void exportDoctorsWorkExcel(@RequestBody QuerySurveyDeptListRequest request, HttpServletRequest request1, HttpServletResponse response1) throws IOException {

        List<SurveyPlanWorkListResponse> planWorkListResponses = new ArrayList<>();
//        List<SurveyPlanDeptListResponse> surveyPlanDeptListResponses = patientSatisfactionSurveyDAO.queryDoctorWorkList1(request);
//        for(SurveyPlanDeptListResponse surveyPlanDeptListResponse:surveyPlanDeptListResponses){
//            SurveyPlanWorkListResponse response = new SurveyPlanWorkListResponse();
//            response.setOrgName("杭州市第三人民医院");
//            response.setDoctorId(surveyPlanDeptListResponse.getDoctorId());
//            response.setDoctorName(surveyPlanDeptListResponse.getDoctorName());
//            response.setBack(surveyPlanDeptListResponse.getBack());
//            response.setPush(surveyPlanDeptListResponse.getPush());
////            BigDecimal num = new BigDecimal(surveyPlanDeptListResponse.getC()*100);
////            BigDecimal bnum = num.setScale(2, RoundingMode.HALF_UP);
////            response.setC(String.valueOf(bnum));
//            // Integer integer = patientSatisfactionSurveyDAO.queryDcotrorCount(surveyPlanDeptListResponse.getDoctorId(), request.getBeginDate(), request.getEndDate(), request.getQuestionnaireId());
//            // log.info("输出===============》"+integer);
////            BigDecimal num = new BigDecimal(surveyPlanDeptListResponse.getC()*100);
//            //double result = (double)  integer/Integer.valueOf(surveyPlanDeptListResponse.getBack());
////            BigDecimal num = new BigDecimal(result*100);
//            BigDecimal num = null;
//            if (CommonUtils.isNull(surveyPlanDeptListResponse.getC())){
//                num = new BigDecimal(new Double(0)*100);
//
//            } else {
//                num = new BigDecimal(surveyPlanDeptListResponse.getC()*100);
//            }
//            BigDecimal bnum = num.setScale(2, RoundingMode.HALF_UP);
//            response.setC(String.valueOf(bnum));
//
//            if(CommonUtils.isNotEmpty(surveyPlanDeptListResponse.getDoctorId())){
//                QuerySurveyDeptListRequest req = new QuerySurveyDeptListRequest();
//                req.setDoctorId(surveyPlanDeptListResponse.getDoctorId());
//                req.setQuestionnaireId(request.getQuestionnaireId());
//                req.setBeginDate(request.getBeginDate());
//                req.setEndDate(request.getEndDate());
//                List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = patientSatisfactionSurveyDAO.querySurveyAverByDoctorId(req);
//                response.setSurveyPlanTitleListResponses(surveyPlanTitleListResponses);
//            }
//            planWorkListResponses.add(response);
//        }
        log.info(JSONUtils.writeValueAsString(request));
        QueryDoctorTotalResponse queryDoctorTotalResponse = patientSatisfactionSurveyDAO.queryDoctorWorkListTotal(request);
        if (CommonUtils.isNull(queryDoctorTotalResponse.getTotalSum())) {

            queryDoctorTotalResponse.setTotalSum("0.00");
        } else {
            Double aDouble = Double.valueOf(queryDoctorTotalResponse.getTotalSum());
            log.info("=================>aDouble" + aDouble);
            BigDecimal num = new BigDecimal(aDouble * 100);
            BigDecimal bigDecimal = num.setScale(2, RoundingMode.HALF_UP);
            queryDoctorTotalResponse.setTotalSum(String.valueOf(bigDecimal));

        }

        log.info("---------------------------------》统计" + JSONUtils.writeValueAsString(queryDoctorTotalResponse));
        List<SurveyPlanDeptListResponse> surveyPlanDeptListResponses = patientSatisfactionSurveyDAO.queryDoctorWorkListNew(request);
        for (SurveyPlanDeptListResponse surveyPlanDeptListResponse : surveyPlanDeptListResponses) {
            SurveyPlanWorkListResponse response = new SurveyPlanWorkListResponse();
            response.setOrgName("杭州市第三人民医院");
            response.setDoctorId(surveyPlanDeptListResponse.getDoctorId());
            response.setDoctorName(surveyPlanDeptListResponse.getDoctorName());
            response.setBack(surveyPlanDeptListResponse.getBack());
            response.setPush(surveyPlanDeptListResponse.getPush());
            BigDecimal num = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getC())) {
                num = new BigDecimal(new Double(0) * 100);

            } else {
                num = new BigDecimal(surveyPlanDeptListResponse.getC() * 100);
            }
            BigDecimal bnum = num.setScale(2, RoundingMode.HALF_UP);
            response.setC(String.valueOf(bnum));


            BigDecimal a = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getD())) {
                a = new BigDecimal(new Double(0) * 100);

            } else {
                a = new BigDecimal(surveyPlanDeptListResponse.getD() * 100);
            }
            BigDecimal anum = a.setScale(2, RoundingMode.HALF_UP);
            response.setD(String.valueOf(anum));

            BigDecimal b = null;
            if (CommonUtils.isNull(surveyPlanDeptListResponse.getE())) {
                b = new BigDecimal(new Double(0) * 100);

            } else {
                b = new BigDecimal(surveyPlanDeptListResponse.getE() * 100);
            }
            BigDecimal bnum1 = b.setScale(2, RoundingMode.HALF_UP);
            response.setE(String.valueOf(bnum1));


            if (CommonUtils.isNotEmpty(surveyPlanDeptListResponse.getDoctorId())) {
                QuerySurveyDeptListRequest req = new QuerySurveyDeptListRequest();
                req.setDoctorId(surveyPlanDeptListResponse.getDoctorId());
                req.setQuestionnaireId(request.getQuestionnaireId());
                req.setBeginDate(request.getBeginDate());
                req.setEndDate(request.getEndDate());
                List<SurveyPlanTitleListResponse> surveyPlanTitleListResponses = new ArrayList<>();
                response.setSurveyPlanTitleListResponses(surveyPlanTitleListResponses);
            }
            log.info("---------------------------------》统计--------------------->" + JSONUtils.writeValueAsString(queryDoctorTotalResponse));
            response.setQueryDoctorTotalResponse(queryDoctorTotalResponse);
            planWorkListResponses.add(response);
        }

        if (CollectionUtils.isEmpty(planWorkListResponses)) {
            throw new ServiceException("没有要导出的数据");
        }
        logger.info("planWorkListResponses======" + JSONUtils.writeValueAsString(planWorkListResponses));

        byte[] data = SatisfactionSurveyExcelUtil.getExcelAsByteArray2(planWorkListResponses);
        String fileName = null;
        fileName = URLEncoder.encode("医生满意度统计.xlsx", "UTF-8");
        response1.reset();
        response1.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response1.addHeader("Content-Length", "" + data.length);
        response1.setContentType("application/vnd.ms-excel;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response1.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();

    }

}
